/*
 * Copyright (c) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import { isSymbolNode } from '../../../utils/is.js';
import { createSubScope } from '../../../utils/scope.js';
/**
 * Compile an inline expression like "x > 0"
 * @param {Node} expression
 * @param {Object} math
 * @param {Object} scope
 * @return {function} Returns a function with one argument which fills in the
 *                    undefined variable (like "x") and evaluates the expression
 */

export function compileInlineExpression(expression, math, scope) {
  // find an undefined symbol
  var symbol = expression.filter(function (node) {
    return isSymbolNode(node) && !(node.name in math) && !scope.has(node.name);
  })[0];

  if (!symbol) {
    throw new Error('No undefined variable found in inline expression "' + expression + '"');
  } // create a test function for this equation


  var name = symbol.name; // variable name

  var subScope = createSubScope(scope);
  var eq = expression.compile();
  return function inlineExpression(x) {
    subScope.set(name, x);
    return eq.evaluate(subScope);
  };
}